package com.kws.auth.controller;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kws.auth.form.LoginMessageBody;
import com.kws.auth.form.RegisterUserBody;
import com.kws.auth.util.CodeUtil;
import com.kws.common.log.annotation.Log;
import com.kws.common.log.enums.BusinessType;
import com.kws.system.api.domain.Rq.QueryWeixinUserInfoRq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.kws.auth.form.LoginBody;
import com.kws.auth.service.SysLoginService;
import com.kws.common.core.domain.R;
import com.kws.common.core.utils.JwtUtils;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.service.TokenService;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.model.LoginUser;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * token 控制
 * 
 * @author zhangyh
 */
@Api(value = "sysCommonLogin", tags = "统一登录管理模块")
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("注册用户")
    @PostMapping("/register/user")
    @Log(title = "注册系统", businessType = BusinessType.REGISTER)
    public R registerUserUser(@RequestBody RegisterUserBody body){
        return sysLoginService.registerUserUser(body);
    }

    @PostMapping("login")
    @ApiOperation(value = "web端登录")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation("短信验证码登陆")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    @PostMapping("/message/login")
    public R<?> messageLogin(@RequestBody LoginMessageBody from){
        // 用户登录
        LoginUser userInfo = sysLoginService.messageLogin(from);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation("获取验证码-图像验证码")
    @GetMapping("/query/checkCode")
    public void getCheckCode(HttpServletResponse response){
        String code = String.valueOf(10000 + new Random().nextInt(90000));
        BufferedImage bufferedImage = CodeUtil.buildImg(code ,300, 100, 2, 50);
        //存储验证码，用于用户输入校验
        redisTemplate.opsForValue().set(code,code);
        //禁止图片缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //设置响应格式
        response.setContentType("image/jpeg");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpeg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("根据密码加验证码方式登陆")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    @PostMapping("/login/code")
    public R loginCode(@RequestBody LoginBody form){
        if (StringUtils.isEmpty(form.getCode())){
            return R.fail("验证码不能为空");
        }
        String code = redisTemplate.opsForValue().get(form.getCode());
        if (StringUtils.isEmpty(code) || !code.equals(form.getCode())){
            return R.fail("验证码不正确");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation("小程序微信登陆")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    @GetMapping("/weixin/smallProgram/login")
    public R smallProgramLogin(@RequestParam String code,@RequestParam String channel){
        LoginUser userInfo = sysLoginService.smallProgramLogin(code,channel);
        if (null == userInfo.getSysUser()){
            Map<String,String> map = new HashMap<>();
            map.put("access_token", null);
            map.put("expires_in", null);
            map.put("openId",userInfo.getOpenId());
            map.put("check","0");
            return R.ok(map);
        }
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation("根据openId绑定用户信息")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    @GetMapping("/bind/userOpenId")
    public R bindUserOpenId(@RequestParam String openId,@RequestParam String phone,@RequestParam String channel){
        LoginUser userInfo = sysLoginService.bindUserOpenId(openId,phone,channel);
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation(value = "App微信登录")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    @GetMapping("/weixin/login")
    public R weiXinLogin(@RequestParam String code,@RequestParam(required = false) String channel){
        LoginUser userInfo = sysLoginService.weiXinLogin(code,channel);
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation(value = "退出登录")
    @Log(title = "退出登陆", businessType = BusinessType.LOGOUT)
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @ApiOperation(value = "token刷新")
    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

}
